<?php
require_once('../../libraryfiles/config.php');
require_once '../../libraryfiles/SendEmail.php';
$action = isset($_GET['action']) ? $_GET['action'] : '';
switch($action){

	case 'add' :
		addUser();
		break;

	case 'publish':
		publishSelect();
		break;

	case 'muliDelete' :
		muliDelete();
		break;
	case 'delete':
		delete();
		break;
	case 'aproved':
		aproved_premium_account();
		break;
	case 'changepassword':
		changePassword();
		break;
	case 'updateprofile':
		updateUserProfile();
		break;
	default :
		header('Location: index.php');
		exit();
}

function addUser(){
	$ID = isset($_POST['hidid'])?$_POST['hidid']:"";
	$first_name = trim($_POST['txttitle']);
	$last_name = trim($_POST['txtmeta_key']);
	$username = trim($_POST['txtmeta_desc']);
	$email = $_POST['txtemail'];
	$conemail = $_POST['txtconemail'];
	$password = $_POST['txtpass'];
	$conpass = $_POST['txtconpass'];
	$type = $_POST['type'];
	if(empty($ID)){
		if(empty($username)){
			header('Location:'.base_url_admin.'/user/index.php?view=add&error=required');
			exit();
		}if(empty($email)){
			header('Location:'.base_url_admin.'/user/index.php?view=add&error=required');
			exit();
		}if(empty($password)){
			header('Location: '.base_url_admin.'/user/index.php?view=add&error=required');
			exit();
		}if(empty($type)){
			header('Location: '.base_url_admin.'/user/index.php?view=add&error=required');
			exit();
		}if($email != $conemail){
			header('Location: '.base_url_admin.'/user/index.php?view=add&error=notequalemail');
			exit();
		}if($password != $conpass){
			header('Location: '.base_url_admin.'/user/index.php?view=add&error=notequalpass');
			exit();
		}if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
			header('Location: '.base_url_admin.'/user/index.php?view=add&error=invalidemail');
			exit();
		}
	}
	$detectExist_q = '';
	if(!empty($ID)){
		$detectExist_q = '';
		$modify = true;
		$link = "&id=" . $ID;
		$detectExist_q .= " AND id != " . $ID;
	}
	if(existRecord("tbluser","username = '$username' $detectExist_q")){
		header('Location: '.base_url_admin.'/user/index.php?view=add&error=' . urlencode('Name already taken. Please choose another one'));
		exit();
	}
	else if($modify){
		if ('' != $password) {
			$passwordLog = EnscryptPassword($password);
			$sql_u = "UPDATE tbluser SET first_name = '$first_name', last_name = '$last_name', username = '$username', email = '$email', user_pass = '$passwordLog', mdate=NOW(),user_type_id = '$type' WHERE id = $ID";
		} else {
			$sql_u = "UPDATE tbluser SET first_name = '$first_name', last_name = '$last_name', username = '$username', email = '$email', mdate=NOW(),user_type_id = '$type' WHERE id = $ID";
		}
		mysql_query($sql_u);

	} else {
		$passwordLog = EnscryptPassword($password);
		$sql   = "INSERT INTO tbluser(first_name, last_name, username, user_pass, email, cdate,user_type_id, status) VALUES ('$first_name', '$last_name', '$username','$passwordLog','$email', NOW(),'$type',1)";
		mysql_query($sql);
	}
	header('Location:'.base_url_admin.'/user/index.php');
	exit();

}
 function updateUserProfile(){
		if(isset($_POST['btnsave'])){
			$mailsql = "SELECT * FROM tbluser WHERE email = '".$_POST['txtemail']."' AND id != '".@$_SESSION['acc_id']."'";
			$querymailsql = mysql_query($mailsql);
			$querymail = mysql_fetch_object($querymailsql);
			if(!empty($querymail)){
				header('location:'.base_url_admin.'/user/index.php?view=userprofile&edit=1&message=mailexist');
				exit();
			}
			if(!filter_var($_POST['txtemail'], FILTER_VALIDATE_EMAIL)) {
				header('location:'.base_url_admin.'/user/index.php?view=userprofile&edit=1&message=invalidformat');
				exit();
			}
				$FirstName = $_POST['txt_firstname'];
				$LastName = $_POST['txt_lastname'];
				$Email = $_POST['txtemail'];
				$UserName = $_POST['txtusername'];
				$Address  = $_POST['txtaddress'];
				$Phone 	  = $_POST['txtphone'];
				$sql = "UPDATE tbluser SET first_name = '".$FirstName."', last_name = '".$LastName."', email = '".$Email."',username = '".$UserName."',address='".$Address."',phone='".$Phone."' WHERE id='".@$_SESSION['acc_id']."'";
				$query = mysql_query($sql);
				header('location:'.base_url_admin.'/user/index.php?view=userprofile&message=prosuccess');
				exit();

		}
	}
	function changePassword(){
				$OldPassword = EnscryptPassword($_POST['txtOldPassword']);
				$NewPassword = $_POST['txtpass'];
				$ConfirmPassword = $_POST['txtconpass'];
				if(empty($OldPassword) || empty($NewPassword) || empty($ConfirmPassword)){
						header('location:'.base_url_admin.'/user/index.php?view=changepassword&edit=1&message=required');
						exit();
					}
				if($NewPassword != $ConfirmPassword){
					header('location:'.base_url_admin.'/user/index.php?view=changepassword&edit=1&message=compass');
					exit();
				}
				$mysqlUserproflie = mysql_query("SELECT *FROM tbluser WHERE user_pass='".$OldPassword."' AND id='".@$_SESSION['acc_id']."'");
				$Result = mysql_fetch_object($mysqlUserproflie);
				if(empty($Result)){
					header('location:'.base_url_admin.'/user/index.php?view=changepassword&edit=1&message=errorpas');
						exit();
				}else{
					$Newpasword = EnscryptPassword($NewPassword);
					$sql = "UPDATE tbluser SET user_pass = '".$Newpasword."' WHERE id='".@$_SESSION['acc_id']."'";
					$query = mysql_query($sql);
					header('location:'.base_url_admin.'/user/index.php?view=userprofile&message=prosuccess');
					exit();
				}
	}
	function publishSelect(){

		if(isset($_POST['id'])){
			if(isset($_GET['publish']) && (int)$_GET['publish']>=0 && (int)$_GET['publish']<=1){
				$state = (int)$_GET['publish'];
			}
			else{
				header('Location: '.base_url_admin.'/user/index.php');
				exit();
			}
			//Statement to get selected id
			$id = (is_array($_POST['id']))?implode(',',$_POST['id']):$_POST['id'];

			//Statment to delete selected id
			$sql = "UPDATE tbluser SET status = $state WHERE id IN ($id)";
			mysql_query($sql);
		}
		header('Location:'.base_url_admin.'/user/index.php');
		exit();

	}
	function muliDelete()
	{
		if(isset($_POST['id'])){
			$id = (is_array($_POST['id']))?implode(',',$_POST['id']):$_POST['id'];
			$sql = "DELETE FROM tbluser WHERE id IN ($id)";
			mysql_query($sql);
		}
		header('Location:'.base_url_admin.'/user/index.php');
		exit();

	}
	function delete(){
		if(isset($_GET['id'])){
			$sql = "DELETE FROM ".Tbluser::Tbluser."  WHERE ". Tbluser::id."=".@$_GET['id'];
			mysql_query($sql);
//			$unlinkProduct = mysql_query("SELECT id FROM tblproduct WHERE owner='".@$_GET['id']."'");
//			$rowUnlinkProduct = @mysql_fetch_obect($unlinkProduct);
//			echo 11;die;
//			if(!empty($rowUnlinkProduct)){
//				$sql_image = mysql_query("SELECT *FROM tblimage WHERE product_id='".@$rowUnlinkProduct->id."'");
//				while ($rowUnlinkImg = mysql_fetch_object($sql_image)){
//					if (file_exists ('../../product/images/' .$rowUnlinkImg->images)) {
//						unlink('../../product/images/'.$rowUnlinkImg->images);
//					}
//					if (file_exists ('../../product/images/' .$rowUnlinkImg->thumbnail)) {
//						unlink('../../product/images/'.$rowUnlinkImg->thumbnail);	
//					}
//					if (file_exists ( '../../product/images/' .$rowUnlinkImg->original_img)) {
//						unlink('../../product/images/'.$rowUnlinkImg->original_img);
//					}
//				}
//				
//				mysql_query("DELETE FROM tblimage WHERE product_id='".$rowUnlinkProduct->id."'");
//				mysql_query("DELETE FROM tblproduct WHERE owner='".$_GET['id']."'");
//				mysql_query("DELETE FROM tblproduct_in_pharmacy WHERE pharmacy_id='".$_GET['id']."'");
//			}
			header('Location:'.base_url_admin.'/user/index.php?messaget=delete');
			exit();
		}
			
	}
	function aproved_premium_account(){
		date_default_timezone_set('Asia/Phnom_Penh');
		if(!empty($_GET['activateid'])&& !empty($_GET['email'])){
			$id = isset($_GET['id']) ? (int) $_GET['id']: '';
			@mysql_query("UPDATE tblproduct SET post_type=1 WHERE owner='".$id."'");
			$account_type_id = !empty($_GET['account_type_id'])? ",account_type_id=".$_GET['account_type_id'] :"";
			$user_type_id = ($_GET['user_type_id']==3)? 2 : $_GET['user_type_id'];
			 $sqlStatment = "UPDATE tbluser SET user_type_id = '".$user_type_id."', status=1,activated_status=1 $account_type_id WHERE email='".$_GET['email']."' AND activate='".$_GET['activateid']."' AND id='".$id."'";
			$UpdateSuccess = mysql_query($sqlStatment);
			if($UpdateSuccess){
				if(!empty($account_type_id)){
					mysql_query("DELETE FROM tbl_refcode WHERE ref_type='user_upgrade' AND ref_oject_id='".$id."' ");
				}
				$accounttype_id = mysql_query("SELECT *FROM tbluser_account_type WHERE id IN (SELECT account_type_id FROM tbluser WHERE id='".$id."') LIMIT 1");
				$acc_id = mysql_fetch_object($accounttype_id);
				$expired_Date = $acc_id->account_expire;
				$Day = 86400*$expired_Date;
				$CurDate = strtotime('now');
				$TotalExpire = $CurDate + $Day;
				mysql_query("UPDATE tblpharmacy SET expire_date='".$TotalExpire."' WHERE user_id='".$id."'");
				$transport = new SendEmail();
				$mail = $_GET['email'];
				$Name = $_GET['name'];
				$name = $Name;
				$email = $mail;
				$header = General::USERNAME;
				$subjects = "Account Activation by psarinternet";
				$BodyHeader ="Account Activation!";
				$BodyMessage = "Dear ".$Name.", <br/> <p>Your account has been activated. We welcome you to our online community and trust that together.</p>.<br/> Enjoy the experience!<br/>Kind Regards,<br/>Psarinternet Team";
				$transport = $transport->SendMail($name, $email, $base=0, $header, $subjects, $BodyHeader, $BodyMessage);
				header('location:'.base_url_admin.'/user/index.php?view=list&message=aproved&name='.$Name);
				exit();
			}else{
				header('location:'.base_url_admin.'/user/index.php?view=list&message=invalid');
				exit();
			}
		}else{
			header('location:'.base_url_admin.'/user/index.php?view=list&message=invalid');
			exit();
		}

	}

